import { v4 as uuidv4 } from 'uuid';

type ExcelTypeDict = {
  [key in HandleExcelType]?: {
    type: HandleExcelType;
    label: string;
    explain: string; 
    value: string;
  };
}
// excelde处理类型
export const handleExcelTypeDict:ExcelTypeDict = {
  parse: {
    type: 'parse',
    label: '解析文件',
    explain: '解析Excel文件',
    value: 'parse'
  },
  merge: {
    type: 'merge',
    label: '合并数据',
    explain: '根据指定字段合并表头不一样的Excel文件,冲突字段保留最新值',
    value: 'merge'
  },
  freeMerge: {
    type: 'freeMerge',
    label: '合并Excel',
    explain: '根据指定字段合并表头不一样的Excel文件,冲突字段保留最新值',
    value: 'freeMerge'
  },
  dedupe: {
    type: 'dedupe',
    label: '数据去重',
    explain: '根据指定字段进行数据去重',
    value: 'dedupe'
  },
  export: {
    type: 'export',
    label: '导出文件',
    explain: '导出 Excel 文件',
    value: 'export'
  },
  filter: {
    type: 'filter',
    label: '筛选数据',
    explain: '根据指定字段筛选数据',
    value: 'filter'
  },
  modify: {
    type: 'modify',
    label: '修改数据',
    explain: '根据指定字段修改数据',
    value: 'modify'
  },
  desensitization: {
    type: 'desensitization',
    label: '数据脱敏',
    explain: '根据指定字段脱敏数据',
    value: 'desensitization'
  }
}

export const getArrHandleType = () => {
  return Object.keys(handleExcelTypeDict).map(key => handleExcelTypeDict[key as keyof typeof handleExcelTypeDict]);
}

// 处理合并单元格数据，生成 Ant Table 需要的 rowSpan/colSpan
export const processMerges = (data: ExcelRow[], merges: MergeInfo[]) => {
  const mergedCells = new Map<string, { rowSpan: number; colSpan: number }>();
  merges.forEach(merge => {
    for (let r = merge.s.r; r <= merge.e.r; r++) {
      for (let c = merge.s.c; c <= merge.e.c; c++) {
        mergedCells.set(`${r}-${c}`, {
          rowSpan: r === merge.s.r ? merge.e.r - merge.s.r + 1 : 0,
          colSpan: c === merge.s.c ? merge.e.c - merge.s.c + 1 : 0
        });
      }
    }
  });

  return data.map((row, rowIndex) => {
    const newRow: ExcelRow & Record<string, any> = { ...row };
    Object.keys(row).forEach((key, colIndex) => {
      const cellInfo = mergedCells.get(`${rowIndex}-${colIndex}`);
      if (cellInfo) {
        newRow[key] = {
          children: row[key],
          props: cellInfo
        };
      }
    });
    return {
      ...newRow,
      key: uuidv4()
    }
  });
};

// 处理导出
export const handleExport = (data: any, fileName: string) => {
  const blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${fileName || 'export.xlsx'}`;
  link.click();
}


export function debounce(fn: Function, delay: number) {
  let timer: NodeJS.Timeout | null = null;
  return function (...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  } 
}
